package com.jnc.pay.biz.common.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import com.jnc.pay.biz.common.service.PaymentService;
import com.jnc.pay.biz.common.vo.PayReq;
import com.jnc.pay.constant.SysConstant;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @Auther: jjn
 * @Date: 2020/6/24 17:42
 * @Desc:
 */
@Slf4j
public abstract class AbstractAliPay implements PaymentService {

    /**
     * 填充支付请求参数
     * @param req
     * @return
     */
    protected Map<String, Object> fillPayReq(PayReq req){
        String price = NumberUtil.div(Integer.toString(req.getTotalFee()),
                Integer.toString(100), req.getScale()).toString();
        StringBuffer sb = new StringBuffer();
        sb.append("trade_id=").append(req.getTradeId())
                .append("&app_order_id=").append(req.getAppOrderId())
                .append("&out_app_id=").append(req.getAppId());
        String backParam = "";
        try {
            backParam = URLEncoder.encode(sb.toString(), SysConstant.CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            log.error("[Alipay] fill request params error: {}", e);
            return null;
        }
        Map<String, Object> map = MapUtil.newHashMap();
        map.put("out_trade_no", req.getTradeId());
        map.put("total_amount", price);
        map.put("subject", req.getBody());
        map.put("body", req.getDetail());
        map.put("seller_id", req.getAlipayConfig().getSellerId());
        map.put("passback_params", backParam);
        return map;
    }
}
